package com.faya.green.service.impl;

import com.faya.green.abnormal.ServiceException;
import com.faya.green.common.Constant;
import com.faya.green.dao.authority.OrgPostDao;
import com.faya.green.dao.authority.OrganizationDao;
import com.faya.green.dao.authority.PostDao;
import com.faya.green.dao.authority.PostUserDao;
import com.faya.green.enumeration.ResultEnum;
import com.faya.green.enumeration.StatusEnum;
import com.faya.green.model.*;
import com.faya.green.model.web.OrganizationWeb;
import com.faya.green.service.OrganizationService;
import com.faya.green.utils.CommonUtils;
import com.faya.green.utils.FileUtils;
import com.faya.green.utils.ImgUtils;
import com.faya.green.utils.PropertiesUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
 * 用户 ：LX
 * 创建时间： 2018/7/26. 23:31
 * 地点：广州
 * 目的: 根机构|部门 业务层
 * 结果：
 */
@Service
public class OrganizationServiceImpl implements OrganizationService {

    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private OrganizationDao organizationDao;
    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private OrgPostDao orgPostDao;
    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private PostDao postDao;
    //压制全部警告
    @SuppressWarnings("all")
    @Autowired
    private PostUserDao postUserDao;

    @Override
    public List<Organization> getAllRootNode() {
        return organizationDao.getAllRootNode();
    }


    @Transactional(rollbackFor = Exception.class) //事务回滚
    @Override
    public ResultJson addOrUpdOraganization(String sonId, Organization organization, MultipartFile file, String operateType) {
        ResultJson resultJson = new ResultJson();

        /*检测关键数据是否未填写*/
        if ("2".equals(operateType)){
            String id = organization.getId();
            if (CommonUtils.checkNull(id)){
                throw new ServiceException("更新操作未发现更新主键");
            }
        }
        if ("3".equals(operateType)){
            if (CommonUtils.checkNull(sonId)){
                throw new ServiceException("未发现原始节点，请刷新重试");
            }
        }
        if (CommonUtils.checkNull(organization.getName())){
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
            resultJson.setMsg("机构名不能为空");
            return resultJson;
        }

        if (CommonUtils.checkNull(organization.getFatherorgNode())){
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
            resultJson.setMsg("管辖机构关键数据缺失");
            return resultJson;
        }
        if (CommonUtils.checkNull(organization.getFatherorgName())){
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
            resultJson.setMsg("管辖机构名不能为空");
            return resultJson;
        }

        if (CommonUtils.checkNull(organization.getIsRoot())){
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
            resultJson.setMsg("是否根机构未选择");
            return resultJson;
        }


        //是根机构
        if (Constant.IS_ROOT.equals(organization.getIsRoot())){
            if (Constant.IS_NO_DEPORORG.equals(organization.getIsDepOrOrg())){
                resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
                resultJson.setMsg("不能既是根机构，又是部门类型，数据异常，请比对后重试");
                return resultJson;
            }
            if (!CommonUtils.checkNull(organization.getOrgDep())){
                organization.setType(organization.getOrgDep());
            }
            //根机构则要清空隶属机构和部门数据,因为根机构不存在隶属关系
            organization.setFatherNode(null);
            organization.setFatherName(null);
            //根机构的等级是从0开始
            organization.setLevlet(0);

        //不是根机构
        } else if (Constant.IS_NO_ROOT.equals(organization.getIsRoot())){

            //隶属机构数据
            if (CommonUtils.checkNull(organization.getFatherNode())) {
                //获取根机构的部门类型
                Organization orgRoot = organizationDao.getOrganizationById(organization.getFatherNode());
                if (orgRoot != null){
                    organization.setType(orgRoot.getType());
                    //如果是机构，而且存在隶属某部门的，则添加隶属机构名
                    organization.setFatherName(orgRoot.getName());
                }
            }

            //获取管辖机构的数据 子机构的等级在管辖机构的基础上 + 1
            Organization fatherNode = organizationDao.getOrganizationById(organization.getFatherorgNode());
            if (Constant.IS_DEPORORG.equals(organization.getIsDepOrOrg())){
                //是机构则进一位
                organization.setLevlet(fatherNode.getLevlet() + 1);
            } else {
                //非机构则不加1
                organization.setLevlet(fatherNode.getLevlet());
            }


        } else {
            resultJson.setStatus(ResultEnum.RESULT_ERROR.getStatus());
            resultJson.setMsg("非机构非部门，数据异常");
            return resultJson;
        }


        //图片处理
        //file.getSize 获取文件的大小，没有则是0，  isEmpty 判空，如果是空则为true
        if (file != null && file.getSize() > 0 && !file.isEmpty()){
            try {
                //更新操作要对旧的图片进行删除操作
                if ("2".equals(operateType)){
                    String img = organization.getImg();
                    String imgName = orgImgHandle(file);
                    organization.setImg(imgName);
                    String imgHred = PropertiesUtil.getConfigValue("orgImg");
                    FileUtils.delectFile(imgHred + img);
                } else {
                    String imgName = orgImgHandle(file);
                    organization.setImg(imgName);
                }

            } catch (IOException e) {
                e.printStackTrace();
                throw new ServiceException("机构图片上传失败");
            }
        }


        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();

        //更新操作
        if ("2".equals(operateType)){
            organization.setUpdateTime(new Date());
            organization.setUpdateUser(user.getId());
            organization.setStatus(StatusEnum.STATUS_UPDATE.getCode());

            organizationDao.updateOrganization(organization);

            resultJson.setStatus(ResultEnum.RESULT_SUCCESS.getStatus());
            resultJson.setMsg("机构修改成功");
            resultJson.setCode("upd");

        } else {
            organization.setCreateUser(user.getId());
            organization.setUpdateUser(user.getId());
            organization.setCreateTime(new Date());
            organization.setUpdateTime(new Date());
            organization.setId(UUID.randomUUID().toString());
            organization.setStatus(StatusEnum.STATUS_ADD.getCode());

            organizationDao.addOrganization(organization);

            resultJson.setStatus(ResultEnum.RESULT_SUCCESS.getStatus());
            resultJson.setMsg("机构添加成功");
            resultJson.setCode("add");
        }

        OrganizationWeb organizationWeb = new OrganizationWeb();

        if ("3".equals(operateType)){
            //对原始节点进行操作
            Organization sonOrg = organizationDao.getOrganizationById(sonId);
            sonOrg.setFatherorgNode(organization.getId());
            sonOrg.setFatherorgName(organization.getName());
            organizationDao.updateOrganization(sonOrg);
            resultJson.setCode("son");

            organizationWeb.setId(organization.getId());
            organizationWeb.setName(organization.getName());
            organizationWeb.setIsDepOrOrg(organization.getIsDepOrOrg());
            organizationWeb.setpId(organization.getFatherorgNode());

            organizationWeb.setSonId(sonId);
            organizationWeb.setSonName(sonOrg.getName());
            organizationWeb.setSonIsDepOrOrg(sonOrg.getIsDepOrOrg());
            organizationWeb.setSonPid(sonOrg.getFatherorgNode());
            resultJson.setObject(organizationWeb);

        } else {
            organizationWeb.setId(organization.getId());
            organizationWeb.setName(organization.getName());
            organizationWeb.setIsDepOrOrg(organization.getIsDepOrOrg());
            organizationWeb.setpId(organization.getFatherorgNode());
            resultJson.setObject(organizationWeb);
        }

        return resultJson;
    }

    @Override
    public List<OrganizationWeb> getAllNode() {

        //查询基础数据
        Organization organization = organizationDao.getOrganizationById(Constant.ORG_BASE);

        if (organization != null){
            //初始化数据
            List<OrganizationWeb> webList = new ArrayList<>();
            OrganizationWeb organizationWeb = new OrganizationWeb();
            organizationWeb.setpId("");
            organizationWeb.setName(organization.getName());
            organizationWeb.setId(organization.getId());
            organizationWeb.setIsDepOrOrg("");
            webList.add(organizationWeb);

            Map map = new HashMap();
            map.put("lists", webList);
            map.put("id", organization.getId());

            //调用递归
            return getAllNode(map);
        } else {
            throw new ServiceException("数据未初始化");
        }

    }

    @Override
    public ResultJson getOrganization(String id) {

        Organization organization = organizationDao.getOrganizationByIdtransformZh(id);
        if (organization == null){
            throw new ServiceException("未找到机构|部门数据");
        }
        if (StatusEnum.STATUS_DELETE.getCode().equals(organization.getStatus())){
            throw new ServiceException("该机构已删除");
        }

        return new ResultJson(null, ResultEnum.RESULT_SUCCESS.getStatus(),"查询成功", organization);

    }

    @Override
    public Organization getOrganizationById(String id) {
        return organizationDao.getOrganizationById(id);
    }

    @Transactional(rollbackFor = Exception.class) //事务回滚
    @Override
    public void delOrganization(String id) {

        if (CommonUtils.checkNull(id)){
            throw new ServiceException("非法请求，ID不能为空");
        }
        if (Constant.ORG_BASE.equals(id)){
            throw new ServiceException("不能删除根节点");
        }

        Organization organization = organizationDao.getOrganizationById(id);
        if (organization == null){
            throw new ServiceException("根据Id找不到对应数据");
        }

        Map map = new HashMap();
        List<OrganizationWeb> webList = new ArrayList<>();
        OrganizationWeb organizationWeb = new OrganizationWeb();
        organizationWeb.setpId("");
        organizationWeb.setName(organization.getName());
        organizationWeb.setId(organization.getId());
        organizationWeb.setIsDepOrOrg("");
        webList.add(organizationWeb);

        map.put("lists", webList);
        map.put("id", organization.getId());
        //调用递归 获取全部节点
        List<OrganizationWeb> allNode = getAllNode(map);
        List<OrgPost> allOrgPost = new ArrayList<>();

        for (OrganizationWeb orgWeb : allNode){
            //判断有无岗位，有岗位的判断有无用户，有用户则不能删除
            String orgId = orgWeb.getId();
            List<OrgPost> orgPostList = orgPostDao.getOrgPostByOrgId(orgId);
            allOrgPost.addAll(orgPostList);
            for (OrgPost orgPost : orgPostList){
                String postId = orgPost.getPostId();
                if (!CommonUtils.checkNull(postId)){
                    List<PostUser> postUserList = postUserDao.getPostUserByPostId(postId);
                    if (postUserList != null && postUserList.size() > 0){
                        throw new ServiceException("还有机构下存在用户，不能执行删除");
                    }
                }
            }
        }

        //org图片的路径
        String imgHred = PropertiesUtil.getConfigValue("orgImg");

        //执行删除操作,会删除带岗位的数据
        for (OrgPost orgPost : allOrgPost){
            String postId = orgPost.getPostId();
            Post post = postDao.getPostById(postId);

            postDao.delPost(post.getId());
            orgPostDao.delOrgPost(orgPost.getId());

        }

        //删除机构数据
        for (OrganizationWeb orgWeb : allNode){
            String orgId = orgWeb.getId();
            Organization org = organizationDao.getOrganizationById(orgId);
            organizationDao.delOrganization(org.getId());
            //org 图片
            String img = org.getImg();
            if (!CommonUtils.checkNull(img)){
                FileUtils.delectFile(imgHred + img);
            }
        }

    }

    /**
     * 递归查询 某节点下 全部的子节点，用 管辖机关ID 关联
     * @param map lists 数据集合， id 要递归开始的节点ID
     * @return
     */
    private List<OrganizationWeb> getAllNode(Map map){
        List<OrganizationWeb> webList = (List<OrganizationWeb>)map.get("lists");
        String id = (String)map.get("id");

        //查询此节点下的所有子节点
        List<Organization> organizations = organizationDao.findOrganizationByFatherorgNode(id);
        if (organizations != null && organizations.size() > 0){
            for (Organization organization : organizations){
                OrganizationWeb organizationWeb = new OrganizationWeb();
                organizationWeb.setId(organization.getId());
                organizationWeb.setIsDepOrOrg(organization.getIsDepOrOrg());
                organizationWeb.setName(organization.getName());
                organizationWeb.setpId(id);
                webList.add(organizationWeb);

                Map m = new HashMap();
                m.put("lists", webList);
                m.put("id", organization.getId());
                getAllNode(m);
            }
        }

        return webList;
    }


    /**
     * 对部门机构的图片处理
     * @param file 图片
     * @return  name 图片名字
     */
    private String orgImgHandle(MultipartFile file) throws IOException {
        //获得图片文件名包括后缀
        String imgName = file.getOriginalFilename();
        //获取后缀（总后开始找.获得下标）
        String prefix = imgName.substring(imgName.lastIndexOf(".") + 1);
        //转换为小写
        prefix = prefix.toLowerCase();
        if (!ImgUtils.checkImgSuffix(file)){
            throw new ServiceException("图片格式有误");
        }

        String imgHredSize = PropertiesUtil.getConfigValue("orgImgSize");
        if (file.getSize() > Integer.valueOf(imgHredSize)){
            throw new ServiceException("上传图片超过大小限制，请重新上传");
        }

        //新的图片名字 + 后缀
        String newImgName = ImgUtils.newImgName();
        String name = newImgName + "." + prefix;
        //组合成路径
        String imgHred = PropertiesUtil.getConfigValue("orgImg");
        FileUtils.init(imgHred);

        //图片处理
        ImgUtils.imgZip(prefix, file, imgHred, name, 75, 75);
        return name;
    }
}
